package com.yxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.context.BaseContext;
import com.yxy.exception.AddInfoException;
import com.yxy.mapper.FilmMapper;
import com.yxy.mapper.RateMapper;
import com.yxy.pojo.dto.FilmDTO;
import com.yxy.pojo.dto.PageQueryDTO;
import com.yxy.pojo.entity.Film;
import com.yxy.pojo.vo.FilmDetailVO;
import com.yxy.pojo.vo.FilmPageQueryVO;
import com.yxy.service.FilmService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class FilmServiceImpl implements FilmService {

    @Autowired
    private FilmMapper filmMapper;
    @Autowired
    private RateMapper rateMapper;

    /**
     * 影视分页查询
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(PageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<FilmPageQueryVO> page = filmMapper.queryByPage(pageQueryDTO);
        page.getResult().forEach(item -> {
            List<Integer> filmRateList = rateMapper.getRateAll("film", item.getId());
            double rateSum = filmRateList.stream().mapToDouble(rate -> rate).sum();
            if(rateSum != 0){
                item.setRate(rateSum / filmRateList.size() / 2);
            }
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增影视
     * @param filmDTO
     */
    @Override
    public void add(FilmDTO filmDTO) {
        // 判断影视是否存在
        Film f = filmMapper.selectByTitle(filmDTO.getTitle());
        if(f != null){
            throw new AddInfoException("影视已存在！");
        }
        Film film = new Film();
        BeanUtils.copyProperties(filmDTO, film);
        film.setCreateTime(LocalDate.now());
        film.setCreateUser(BaseContext.getCurrentId());
        filmMapper.addFilm(film);
    }

    /**
     * 根据id查询影视详情
     * @param id
     * @return
     */
    @Override
    public FilmDetailVO getById(int id) {
        return filmMapper.selectById(id);
    }

    /**
     * 修改影视
     * @param filmDTO
     */
    @Override
    public void update(FilmDTO filmDTO) {
        Film film = new Film();
        BeanUtils.copyProperties(filmDTO, film);
        film.setUpdateUser(BaseContext.getCurrentId());
        film.setUpdateTime(LocalDate.now());
        filmMapper.updateFilm(film);
    }

}
